using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading.Tasks;

public static class ActionUtil 
{

    public static Task WaitInvokeAsync(ref Action eventVariable, Action<Action> onRemove)
    {
        var tcs = new TaskCompletionSource<bool>();
        Action callback = null;
        callback = () =>
        {
            onRemove?.Invoke(callback);
            tcs.SetResult(true);
        };
        eventVariable += callback;
        return tcs.Task;
    }

    public static Task<T> WaitInvokeAsync<T>(ref Action<T> storage, Action<Action<T>> onRemove)
    {
        var tcs = new TaskCompletionSource<T>();
        Action<T> callback = null;
        callback = (T result) =>
        {
            onRemove?.Invoke(callback);
            tcs.SetResult(result);
        };
        storage += callback;
        return tcs.Task;
    }

    public static Task WaitInvokeAsync2(Action<Action> onAdd, Action<Action> onRemove)
    {
        var tcs = new TaskCompletionSource<bool>();
        Action callback = null;
        callback = () =>
        {
            onRemove?.Invoke(callback);
            tcs.SetResult(true);
        };
        onAdd.Invoke(callback);
        return tcs.Task;
    }

    public static Task<T> WaitInvokeAsync2<T>(Action<Action<T>> onAdd, Action<Action<T>> onRemove)
    {
        var tcs = new TaskCompletionSource<T>();
        Action<T> callback = null;
        callback = (T result) =>
        {
            onRemove?.Invoke(callback);
            tcs.SetResult(result);
        };
        onAdd.Invoke(callback);
        return tcs.Task;
    }

}
